<template>
	<div class="container">
		<a-row :gutter="20" justify="end">
			<a-col :span="2" class="py-4 text-center">
				<a-space>
					<a-button @click="closeTab('/yanshou')">
						<close-outlined />关闭
					</a-button>
				</a-space>
			</a-col>
		</a-row>
		<h2 style="text-align: center;margin-bottom: 30px;">
			查看验收单<span v-if="formState.is_weighbridge === 1" style="color: red">(地磅)</span>
		</h2>
		<a-form ref="formRef" :model="formState">
			<a-descriptions title="验收单信息" bordered size="middle">
				<a-descriptions-item label="项目名称">{{ project.name??'' }}</a-descriptions-item>
				<a-descriptions-item label="供应商名称" :span="2">{{ supplier.company_name??'' }}</a-descriptions-item>
				<a-descriptions-item label="采购单编号">{{ formState.purchase_order_code }}</a-descriptions-item>
				<a-descriptions-item label="发货单编号">{{ formState.code }}</a-descriptions-item>
				<a-descriptions-item label="验收类型">
					<a-select v-model:value="formState.ys_type" placeholder="请选择验收类型" :options="yslist" option-filter-prop="label" disabled></a-select>
				</a-descriptions-item>
				<a-descriptions-item label="接收人">{{ formState.receiver }}</a-descriptions-item>
				<a-descriptions-item label="联系电话">{{ formState.receiver_tel }}</a-descriptions-item>
				<a-descriptions-item label="接收时间">{{ formState.deliver_time }}</a-descriptions-item>
				<a-descriptions-item label="接收地点" :span="3">{{ formState.deliver_address }}</a-descriptions-item>
			</a-descriptions>
			<br />
			<a-row :gutter="20">
				<a-col :span="24">
					<a-table :pagination="false" :data-source="formState.materials" :columns="purchaseColumns" :row-key="(record) => record.key">
						<template #bodyCell="{ column, record, index }">
							<template v-if="column.dataIndex === 'id'">{{ index+1 }}</template>
							<template v-else-if="column.dataIndex === 'ys_quantity'">
								<a-form-item :name="['materials', index, 'ys_quantity']" :rules="{required:true, message:'请输入数量'}">
									<a-input v-model:value="formState.materials[index].ys_quantity" disabled placeholder="请输入数量" @change="handleYsQuantity(formState.materials[index].ys_quantity, record)" />
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'use_position'">
								<!--								<a-form-item :name="['materials', index, 'gonghao_id']">-->
								<!--									<a-select v-model:value="formState.materials[index].gonghao_id" :show-search="true" placeholder="请选择" :options="gonghaolist" option-filter-prop="label"></a-select>-->
								<!--								</a-form-item>-->
								<a-tree-select v-model:value="formState.materials[index].use_position" disabled :dropdown-match-select-width="false" :show-search="true" placeholder="请选择详细部位" allow-clear tree-default-expand-all :tree-data="gonghaoTree" tree-node-filter-prop="label" style="width:100%" @change="(id) => changeMaterial(id, record)">
									<template #title="{ label }">{{ label }}</template>
								</a-tree-select>
							</template>
							<template v-else-if="column.dataIndex === 'position'">
								<a-form-item :name="['materials', index, 'position']">
									<a-input v-model:value="formState.materials[index].position" placeholder="详细部位" disabled />
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'brand_id'">
								<a-form-item :name="['materials', index, 'brand_id']">
									<a-select v-model:value="formState.materials[index].brand_id" :options="brandList" placeholder="请选择品牌" disabled />
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'art_indexes'">
								<span v-for="(item, ii) in record.art_indexes" :key="ii" class="mr-5">
									{{ artIndexesGongHaos.find(i => i.value === item.gonghao_id)?.label }};
								</span>
							</template>
							<template v-else-if="column.dataIndex === 'memo'">
								<a-form-item :name="['materials', index, 'memo']">
									<a-input v-model:value="formState.materials[index].memo" placeholder="备注" disabled />
								</a-form-item>
							</template>
						</template>
					</a-table>
				</a-col>
			</a-row>
			<div>
				<a-row v-if="realFileList.length" :gutter="24">
					<a-col :span="24" class="py-4 text-right">
						<a-form-item label="发货附件" name="real_pic_path">
							<template v-for="item in realFileList" :key="item.url">
								<a target="_blank" :href="item.url">{{ item.name }}</a><br />
							</template>
						</a-form-item>
					</a-col>
				</a-row>
				<a-row v-if="realPicList.length" :gutter="24">
					<a-col :span="24" class="py-4 text-right">
						<a-form-item label="发货图片" name="real_pic_path"></a-form-item>
					</a-col>
					<a-col v-for="item in realPicList" :key="item.url" :span="6">
						<div class="gallery-image">
							<a-image :width="160" :height="160" :src="item.url" />
						</div>
						<p>{{ item.name }}</p>
					</a-col>
				</a-row>
				<a-row v-if="approvedHistory.length" :gutter="24">
					<a-col :span="24" class="py-4 text-right">
						<a-form-item label="验收图片" name="pic_path"></a-form-item>
					</a-col>
					<template v-for="item in approvedHistory" :key="item.id">
						<template v-if="item.pic_path && item.pic_path !== '[]'">
							<a-col v-for="i in JSON.parse(item.pic_path)" :key="i.url" :span="4">
								<div class="gallery-image">
									<a-image :width="160" :height="160" :src="i.url" />
								</div>
								<p>{{ i.name }}</p>
							</a-col>
						</template>
					</template>
				</a-row>
				<a-row v-if="approvedHistory.length" :gutter="24">
					<a-col :span="24" class="py-4 text-right">
						<a-form-item label="验收视频" name="pic_path"></a-form-item>
					</a-col>
					<template v-for="item in approvedHistory" :key="item.id">
						<template v-if="item.video_path && item.video_path !== '[]'">
							<a-col v-for="i in JSON.parse(item.video_path)" :key="i.url" :span="4">
								<video controls :width="160" :height="160">
									<source :src="i.url" type="video/mp4" />
								</video>
							</a-col>
						</template>
					</template>
				</a-row>
			</div>
			<a-tabs v-model:activeKey="activeTab">
				<a-tab-pane key="ys_history" tab="验收历史">
					<a-descriptions>
						<template v-for="item in approvedHistory" :key="item.id">
							<a-descriptions-item label="验收时间">{{ item.update_time }}</a-descriptions-item>
							<a-descriptions-item label="验收人">
								<template v-if="item.opr?.manually_signed_file_path">
									<a-image :width="60" :src="item.opr?.manually_signed_file_path" />
								</template>
								<template v-else>
									<span style="padding: 0 5px;">{{ item.opr?.fullname }}</span>
								</template>
								<span v-if="item.opr.is_consignor">({{ item.opr?.parent_user?.company_name }})</span>
							</a-descriptions-item>
							<a-descriptions-item label="验收描述">{{ item.ys_des }}</a-descriptions-item>
						</template>
					</a-descriptions>
				</a-tab-pane>
				<a-tab-pane v-if="formState.is_weighbridge === 1" key="weighbridge_history" tab="过磅记录">
					<a-table :columns="weighbridgeColumns" :data-source="formState.weighbridgeHistorys" :pagination="false" :row-key="(record) => record.id" :scroll="{ x: 1000 }">
						<template #bodyCell="{ column, text }">
							<template v-if="column.type === 'photo'">
								<a-image v-if="!!text" :width="60" :src="text" />
							</template>
						</template>
					</a-table>
				</a-tab-pane>
			</a-tabs>
		</a-form>
		<a-row :gutter="20">
			<a-col :span="24" class="py-4 text-center">
				<a-space>
					<a-button @click="closeTab('/yanshou')">
						<close-outlined />关闭
					</a-button>
				</a-space>
			</a-col>
		</a-row>
	</div>
</template>

<script setup>
import { ref, computed, onMounted, getCurrentInstance, inject } from "vue";
import { Modal } from "ant-design-vue";
import { DeleteOutlined, SaveOutlined, CloseOutlined, PlusOutlined } from "@ant-design/icons-vue";
import { post, treeToList } from "../utils";
import { baseURL } from "../utils/request";
import { useRoute } from "vue-router";
import dayjs from "dayjs";
import { userStore } from "@/store/index.js";
const route = useRoute();
const formState = ref({ materials: [] });
const approvedHistory = ref([]);
const realPicList = ref([]);
const realFileList = ref([]);
const formRef = ref();
const { proxy } = getCurrentInstance();
const gonghaoTree = ref([]); //工号列表
const store = userStore();
const userInfo = store.info;
const isPrint = JSON.parse(route.query.print || 'false');
const brandList = ref([]);
const yslist = [
	{ value: 0, label: "请选择" },
	{ value: 1, label: "钢筋" },
	{ value: 2, label: "混凝土" },
	{ value: 3, label: "周转材料" },
	{ value: 4, label: "机械" },
	{ value: 5, label: "其它" },
	{ value: 6, label: "辅助材料" }
];
const purchaseColumns = ref([
	{
		title: "序号",
		dataIndex: "id",
		width: 60,
		align: "center"
	},
	{
		title: "物资名称",
		dataIndex: "name",
		ellipsis: true
	},
	{
		title: "型号规格",
		dataIndex: "model",
		ellipsis: true
	},
	{
		title: "单位",
		dataIndex: "unit",
		align: "center",
		customRender: ({ text, record, index, column }) => {
			let value = text;
			if (formState.value.ys_type === 2) {
				value = 'm³';
			}
			return value;
		}
	},
	{
		title: "采购数量",
		dataIndex: "quantity",
		align: "center",
		customRender: ({ text, record, index, column }) => {
			return text || record.fangliang;
		}
	},
	{
		title: "发货数量",
		dataIndex: "real_quantity",
		align: "center"
	},
	{
		title: "验收数量",
		dataIndex: "ys_quantity",
		align: "center"
	},
	{
		title: "工号",
		dataIndex: "use_position",
		align: "center",
		width: 100,
	},
	{
		title: "预计浇筑位置",
		dataIndex: "predict_position",
		align: "center",
		customRender: ({ text, record, index, column }) => {
			return record.expected_location;
		}
	},
	{
		title: "技术指标",
		dataIndex: "art_indexes",
		align: "center",
	},
	// {
	// 	title: "详细部位",
	// 	dataIndex: "position",
	// 	align: "center"
	// },
	{
		title: "品牌/厂家",
		dataIndex: "brand_id",
		align: "center"
	},
	{
		title: "备注",
		dataIndex: "memo",
		align: "center"
	}
]);
const weighbridgeColumns = [
	{
		title: "序号",
		dataIndex: "id",
		width: 60,
		align: "center"
	},
	{
		title: "物资名称",
		dataIndex: "material",
		ellipsis: true,
		customRender: ({ text, record, index, column }) => {
			return text?.name;
		}
	},
	{
		title: "型号规格",
		dataIndex: "material",
		ellipsis: true,
		customRender: ({ text, record, index, column }) => {
			return text?.model;
		}
	},
	{
		title: "是否有效",
		dataIndex: "is_effective",
		ellipsis: true,
		customRender: ({ text, record, index, column }) => {
			return text === 1 ? '有效' : '无效';
		}
	},
	{
		title: "单位",
		dataIndex: "material",
		align: "center",
		customRender: ({ text, record, index, column }) => {
			let value = text?.unit;
			if (formState.value.ys_type === 2) {
				value = "m³";
			}
			return value;
		}
	},
	{
		title: "数量",
		dataIndex: "quantity",
		align: "center",
	},
	{
		title: "毛重照片",
		dataIndex: "gross_weight_photo",
		type: 'photo',
		align: "center",
	},
	{
		title: "皮重照片",
		dataIndex: "tare_weight_photo",
		type: 'photo',
		align: "center",
	},
	{
		title: "时间",
		dataIndex: "create_time",
		align: "center",
	},
];
const activeTab = ref('ys_history')
post("dictionary", { root_id: 1414 }).then(data => {
	brandList.value = data;
});

// 物资信息
const purchaseOrderInfo = ref({});
const project = ref({});
const supplier = ref({});

const id = computed(() => route.params.id);
const type = ref();
const artIndexesGongHaos = ref([]);
onMounted(() => {
	post(`supplyOrder/info`, { id: id.value }).then(data => {
		data.pic_path = JSON.parse(data.pic_path || "[]");
		data.video_path = JSON.parse(data.video_path || "[]");
		data.real_pic_path = JSON.parse(data.real_pic_path || "[]");
		for (const file of data.real_pic_path) {
			const suffix = file.url?.split(".").pop();
			if (['jpg', 'jpeg', 'png'].includes(suffix)) {
				realPicList.value.push(file)
			} else {
				realFileList.value.push(file);
			}
		}
		// 非机械和混凝土没有使用部位栏位
		if (![2].includes(data.ys_type)) {
			purchaseColumns.value = purchaseColumns.value.filter((item) => item.dataIndex !== 'use_position' && item.dataIndex !== 'predict_position' && item.dataIndex !== 'art_indexes');
		}
		data.materials = data.materials.map(item => {
			const { quantity, unit, memo, use_date, use_time, time_unit, fangliang, luodu, changdu, add_time, part, real_quantity, ys_quantity, gonghao_id, brand_id, position, expected_location, art_indexes } = item.SupplyOrderMaterial;
			return {
				...item,
				quantity,
				unit,
				memo,
				use_date,
				use_time,
				time_unit,
				fangliang,
				luodu,
				changdu,
				part,
				real_quantity,
				ys_quantity,
				gonghao_id,
				brand_id,
				position,
				add_time: dayjs(add_time).format("YYYY-MM-DD HH:mm:ss"),
				expected_location,
				art_indexes: art_indexes ? JSON.parse(art_indexes) : [],
			};
		});
		type.value = data.purchaseOrder.type;
		if (type.value === 'shangtong') {
			post("dictionary", { root_id: 1069 }).then((data) => {
				artIndexesGongHaos.value = data.map(d => {
					return {
						value: d.id,
						label: d.name
					};
				});
			});
		}
		const purchaseOrder = data.purchaseOrder;
		purchaseOrder.create_time = dayjs(purchaseOrder.create_time).format("YYYY-MM-DD HH:mm:ss");
		purchaseOrderInfo.value = purchaseOrder;
		project.value = data.project;
		supplier.value = data.supplier;
		// if (data.ys_status === 1) {
		// 	data.ys_type = 0;
		// }
		data.ys_type = parseInt(data.ys_type);
		post("department/getTrees", { type: 4, parent_id: data.project_id }).then((treeData) => {
			gonghaoTree.value = treeData;
			const gonghaolist = treeToList(JSON.parse(JSON.stringify(treeData)), []);
			for (const material of data.materials) {
				const { gonghao_id, position } = material || {};
				if (!gonghao_id && !position) continue;
				material.use_position = (gonghaolist.filter((i) => {
					return i.id === (position || gonghao_id)
				})[0] || {}).value || null;
			}
			formState.value = data;
			approvedHistory.value = formState.value.ys_settings.filter((item) => item.ys_status === 2);
			if (isPrint) {
				for (const item of approvedHistory.value) {
					let activeKey = []
					activeKey = approvedHistory.value.reduce((target, item) => {
						target.push(item.pic_path);
						return target;
					}, []);
					activeKey = approvedHistory.value.reduce((target, item) => {
						target.push(item.video_path);
						return target;
					}, activeKey);
					item.activeKey = activeKey;
				}
			}
		});
	});
});

const changeMaterial = (id, record) => {
	const gonghao_id = id.split('-')[1];
	let position = id.split('-').slice(-1)[0];
	if (gonghao_id === position) {
		position = null;
	}
	record.gonghao_id = gonghao_id;
	record.position = position;
};
//上传前校验
const pic_uploading = ref(false);
const video_uploading = ref(false);
const picbeforeUpload = file => {
	pic_uploading.value = true;
};
// 上传并提交文件
const picchangeUpload = ({ file }) => {
	if (file.status === "done") {
		formState.value.pic_path = [
			{
				name: file.name,
				url: file.response.data.url
			}
		];

		pic_uploading.value = false;
		proxy.$message.success("验收图片上传成功");
	}
};
//上传前校验
const videobeforeUpload = file => {
	video_uploading.value = true;
};
// 上传并提交文件
const videochangeUpload = ({ file }) => {
	if (file.status === "done") {
		formState.value.video_path = [
			{
				name: file.name,
				url: file.response.data.url
			}
		];

		video_uploading.value = false;
		proxy.$message.success("验收视频上传成功");
	}
};
function handleYsQuantity(ys_quantity, record) {
	if (parseFloat(ys_quantity) === 0) {
		record.ys_quantity = null;
		return;
	}
	if (parseFloat(ys_quantity) > parseFloat(record.real_quantity)) {
		proxy.$message.error("验收数量不能超过发货数量");
		record.ys_quantity = record.real_quantity;
		return;
	}
}

const closeTab = inject("closeTab");
</script>

<style scoped lang="scss">
.container {
  background: #fff;
  padding: 20px;

  :deep(.ant-table-cell) .ant-form-item {
    margin-bottom: 0;

    .ant-form-item-explain {
      position: absolute;
      bottom: -24px;
    }
  }
}
.gallery-image {
  display: inline-block;
  width: 160px;
  height: 160px;
  overflow: hidden;
  padding:0 5px;
}
</style>
